﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.Logss;
using HamcoWcs.Models.Common;
using Newtonsoft.Json;
using Quartz;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers
{
    /// <summary>文件日志后台服务</summary>
    [DisallowConcurrentExecution]
    public class FileLogWorker : WorkerBase
    {
        public FileLogWorker(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger) : base(wcsDbContext, mapper, logger)
        {
        }

        public override Task Execute(IJobExecutionContext context)
        {
            //Console.WriteLine($"{DateTime.Now:[yyyy-MM-dd HH:mm:ss.fff]}FileLogWorker");
            var clogs = _wcsDbContext.Set<CommunicationLog>().Take(10000).ToList();

            var temps = clogs.GroupBy(x => x.CreatedTime.Date).ToDictionary(k => k.Key, v => v.ToList());

            if (temps.Count == 0) return Task.CompletedTask;


            foreach (var date in temps.Keys)
            {
                var logFileName = Path.Combine(GlobalValue.CommunicateLogFolder, $"{date:yyyyMMdd}");
                if (!File.Exists(logFileName))
                {
                    var fs = new FileStream(logFileName, FileMode.CreateNew, FileAccess.ReadWrite);
                    fs.Close();
                }
                var logs = temps[date].Select(x => JsonConvert.SerializeObject(x, Formatting.None)).ToList();
                bool isLog = false;
                try
                {
                    File.AppendAllLines(logFileName, logs);
                    isLog = true;
                }
                catch (Exception)
                {
                    isLog = false;
                }

                if (isLog)
                {
                    _wcsDbContext.Set<CommunicationLog>().RemoveRange(temps[date]);
                    _wcsDbContext.SaveChanges();
                }

            }
            //var a=temps[1];
            return Task.CompletedTask;
        }



    }
}
